const app = getApp();

import {
  getBanner,
  fav,
  like,
  updateFollow,
  getProfile,
  uploadMedia,
  getComments,
  getShareLink,
  markComment,
  addComments,
  getpddSearch,
  getCodeImg,
  getUserSearch,
  getSiteInfo,
  updataShareCredits,
  getRankList,
} from "../api/common.js";
const compressImage = require('../utils/compressImage');
const util = require('../utils/util');
import Card from '../api/card';


/***
 * 获取用户信息
 */

const getUserInfoFun = function (e) {
  console.log(e);
  if (e.detail.errMsg == "getUserInfo:ok") {
    wx.setStorageSync('scope', true);
    this.getProfiles();
    wx.showLoading({
      title: '登陆中...',
    })
  } else {
    return
  }


}


/**
 * 获取广告轮播图
 */

const getBanners = function (type) {
  let that = this;
  getBanner(type).then(res => {
      let args = {}
      if (res.status == 200) {
        args.banner = res.data;
        args.swiperload = false;
        that.setData(args)
      }
    })
    .catch(err => {
      console.log(err)
    })
}


/**
 * 获取用户信息内容
 */

const getProfiles = function (e) {
  wx.setStorageSync('scope', true);

  getProfile().then(res => {
      wx.hideLoading();
      if (this.data.checkindex == 1) {
        this.getFollowForum({
          page: this.data.page
        });
      }
      if (this.data.isMine) {
        this.getUserMineInfo();
      }
      if (this.data.ismessage) {
        this.getMessages({
          type: 'private',
          page: this.data.page,
        });
      }
      this.setData({
        user: res,
        showlogin: false,
        nologin: false
      })
    })
    .catch(err => {
      wx.hideLoading()
    })
}

/**
 * 取消登陆
 */

const authCancel = function () {
  this.data.currentConfig.show = false;
  this.setData({
    currentConfig: this.data.currentConfig,
  })
}

const addPictures = function (count) {
  let maxSize = 1000;
  let dWidth = wx.getSystemInfoSync().windowWidth;
  var counts = count || 9;
  let that = this
  let images = this.data.imagesubject || []
  wx.chooseImage({
    count: counts,
    success: function (res) {
      wx.showLoading({
        title: '图片上传中',
      })
      if (counts == 1) {
        let file = res.tempFilePaths[0];
        uploadMedia(file).then(res => {
          if (res.url) {
            wx.hideLoading();
            that.setData({
              imagesubject: res.url
            })
          }

        }).catch(err => {
          if (err.message == "未授权登录用户,不能上传") {
            that.data.currentConfig.show = true;
            that.setData({
              currentConfig: that.data.currentConfig,
            })
          }

          wx.showToast({
            title: '图片添加失败'
          })
        })
      } else {
        res.tempFilePaths.forEach(v => {
          wx.getFileInfo({
            filePath: v,
            success: function (res) {
              var cW = res.width,
                cH = res.height,
                rat = 1.1;
              that.cWidth = cW;
              that.cHeight = cH;
            }
          })
          compressImage.getLessLimitSizeImage('canvas', v, maxSize, dWidth, function (img) {
            uploadMedia(img).then(res => {
                if (res.url) {
                  wx.hideLoading();
                  images.push(res.url)
                  if (images.length > 9) {
                    return;
                  } else {
                    that.setData({
                      mediaType: 0,
                      imagesubject: images
                    })
                    wx.showToast({
                      title: '图片添加成功'
                    })
                  }
                } else if (res.status == 500) {
                  wx.showToast({
                    title: '图片添加失败'
                  })
                }
              })
              .catch(err => {
                if (err.message == "未授权登录用户,不能上传") {
                  that.data.currentConfig.show = true;
                  that.setData({
                    currentConfig: that.data.currentConfig,
                  })
                }

                wx.showToast({
                  title: '图片添加失败'
                })
              })
          })

        })
      }
    }
  })
}

const addVideo = function () {
  var t = this;
  console.log('add');
  wx.chooseMedia({
    sourceType: ["album", "camera"],
    compressed: !0,
    maxDuration: t.data.videoDuration,
    success: function (a) {
      wx.showLoading({
        title: '正在上传',
      })
      let filePath = a.tempFiles[0].tempFilePath,
        fileimage = a.tempFiles[0].thumbTempFilePath,
        o = a.tempFiles[0].duration,
        n = a.tempFiles[0].size;
      if (o > t.data.videoDuration) {
        wx.showToast({
          title: "暂不支持60秒以上视频"
        });
        return;
      }
      if (n > 40971520) {
        wx.showToast({
          title: "暂不支持40M以上视频"
        });
        return;
      }
      t.uploadVideoToMedia(filePath);
      if (fileimage) {
        let images = t.data.imagesubject || []
        uploadMedia(fileimage).then(res => {
            images.push(res.url)
            if (images.length >= 9) {
              return;
            } else {
              t.setData({
                imagesubject: images
              })
            }
          })
          .catch(err => {
            if (err.message == "未授权登录用户,不能上传") {
              t.data.currentConfig.show = true;
              t.setData({
                currentConfig: t.data.currentConfig,
              })
            }
            wx.hideLoading()
            wx.showToast({
              title: '视频添加失败'
            })
          })
      }
    },
    fail: function (a) {}
  });
}

const uploadVideoToMedia = function (file) {
  let t = this
  uploadMedia(file).then(res => {
      t.setData({
        mediaType: 1,
        video: res.url
      })
      wx.hideLoading()
      wx.showToast({
        title: '视频添加成功'
      })
    })
    .catch(err => {
      if (err.message == "未授权登录用户,不能上传") {
        t.data.currentConfig.show = true;
        t.setData({
          currentConfig: t.data.currentConfig,
        })
      }
      wx.hideLoading()
      wx.showToast({
        title: '视频添加失败'
      })
    })
}
const audioToMedia = function () {
  let that = this;
  let file = this.data.audio_src;
  uploadMedia(file).then(res => {
      if (res.status === 400) {
        wx.showToast({
          title: '云存储设置错误,请检查',
        })
        return
      }
      console.log(res);

      that.setData({
        audio: res.url,
        is_complete_voice: !0,
        voiceshow: false,
        recording_status: "recording_suc"
      })
      wx.hideLoading()
      wx.showToast({
        title: '语音上传成功'
      })
    })
    .catch(err => {
      if (err.message == "未授权登录用户,不能上传") {
        that.data.currentConfig.show = true;
        that.setData({
          currentConfig: that.data.currentConfig,
        })
      }
      wx.hideLoading()
      wx.showToast({
        title: '语音上传失败'
      })
    })
}

const selectAudio = function (t) {
  if (0 == t) this.setData({
    showRecord: !0
  }), wx.setKeepScreenOn({
    keepScreenOn: !0
  });
  else if (1 == t) {
    var i = this;
    wx.chooseMessageFile({
      count: 1,
      type: "file",
      extension: ["mp3", "m4a"],
      success: function (t) {
        var a = t.tempFiles[0],
          o = a.path.substring(a.path.lastIndexOf(".") + 1).toLowerCase();
        if ("mp3" === o || "m4a" === o)
          if (a.size > 20971520) wx.showToast("暂不支持20M以上音频");
          else {
            uploadMedia(a.path).then(res => {
              var n = {
                fileSize: a.size,
                tempFilePath: res.url,
                duration: 0,
                second: 0
              };
              i.setData({
                showRecord: !1,
                audioInfo: n,
                mediaType: 2
              }), setTimeout(function () {
                i.data.isLocalAudioPlay = !0, i.startPlayAudio(i.data.audioInfo.tempFilePath, !0);
              }, 160);
            })

          }
        else wx.showToast("不支持的音频格式");
      }
    });
  }
}


/**
 * 获取文章评论
 */
const getPostsComments = function (args) {
  getComments(args).then(res => {
      let data = {}
      if (res.length < 10) {
        this.setData({
          isLastPage: true,
          loadtext: '到底啦',
        })
      }
      if (this.data.isReply) {
        this.setData({
          comments: []
        })
        data.comments = [].concat(this.data.comments, res)
        data.page = this.data.page + 1
      } else if (this.data.isBottom) {
        data.comments = [].concat(this.data.comments, res)
        data.page = this.data.page + 1
        data.commentsList = res;
      } else {
        data.comments = res
        data.commentsList = res;
        data.page = this.data.page + 1
      }
      this.setData(data)
    })
    .catch(err => {
      console.log(err)
    })
}


/**
 * 获取积分排名
 */
const getRankLists = function (args) {
  let that = this;
  getRankList(args).then(res => {
      let data = {}
      if (res.length < 10) {
        this.setData({
          isLastPage: true,
          loadtext: '到底啦',
        })
      }
      if (this.data.isBottom) {
        data.rankList = that.data.rankList.concat(res)
        data.page = that.data.page + 1
      } else {
        data.rankList = res
        data.page = that.data.page + 1
      }
      this.setData(data)
    })
    .catch(err => {
      console.log(err)
    })
}

/* 解析链接 */

const jumpAnalysis = function (data) {

  getShareLink(data).then(res => {
    let args = {}
    if (res.status === 200) {
      args.analyzeRes = true
      args.title = res.title

      if (res.type == "video") {
        args.imagesubject = [];
        args.video = res.video;
        args.imagesubject.push(res.thumbnail);
        args.textinput = res.content
        args.format = 'video'
        args.type = 'forums'
        args.videopath = res.video1
        args.mediaType = 1
      }
      if (res.type == "forum") {
        args.imagesubject = res.thumbnail
        args.thumbnail = res.thumbnail[0]
        args.textinput = res.content;
        args.type = 'forums'
        args.format = "standard"
      }
      if (res.type == "post") {
        args.thumbnail = res.thumbnail
        args.textinput = res.content
        args.type = 'forums'
        args.format = "quote"
      }
      //args.video = res.data.video
      this.setData(args)
    }
    wx.hideLoading()
  })


}

const onRecordFinish = function (t) {
  var that = this;
  var i = t.detail.audioInfo;
  wx.showLoading({
    title: '正在上传录音文件',
    mask: true
  })
  uploadMedia(i.tempFilePath).then(res => {
    i.tempFilePath = res.url;
    wx.hideLoading();
    null != i && (i.second = (parseInt(i.duration) / 1e3).toFixed(1), this.setData({
      showRecord: !1,
      audioInfo: i,
      mediaType: 2
    }), wx.setKeepScreenOn({
      keepScreenOn: !1
    }));
  }).catch(err => {
    if (err.message == "未授权登录用户,不能上传") {
      that.data.currentConfig.show = true;
      that.setData({
        showRecord: !1,
        currentConfig: that.data.currentConfig,
      })
    }
    wx.hideLoading()
    wx.showToast({
      title: '录音添加失败'
    })
  })
}

const onAudioDelete = function (t) {
  null != this.innerAudioContext && this.innerAudioContext.stop(),
    this.setData({
      audioInfo: null,
      mediaType: -1
    });
}
const startPlayAudio = function (t, i) {
  null != t && null != this.innerAudioContext && (this.innerAudioContext.volume = i ? 0 : 1,
    t == this.innerAudioContext.src ? (this.innerAudioContext.startTime = 0, this.innerAudioContext.play()) : (this.innerAudioContext.startTime = 0,
      this.innerAudioContext.src = t));
}
const onAudioPlay = function (t) {
  if (t.target.dataset.audio) {
    this.data.audioInfo.tempFilePath = t.target.dataset.audio;
    this.data.audioInfo.duration = t.target.dataset.duration;
    this.data.audioInfo.second = t.target.dataset.second;
    this.setData({
      audioInfo: this.data.audioInfo,
      audioCurrent: t.target.dataset.index,
    })
    if (null != this.innerAudioContext) return this.data.audioInfo.isPlaying ? (this.data.audioInfo.isPlaying = !1,
      this.setData({
        audioInfo: this.data.audioInfo,
      }), void this.innerAudioContext.stop()) : void this.startPlayAudio(this.data.audioInfo.tempFilePath);
  } else {
    if (null != this.innerAudioContext) return this.data.audioInfo.isPlaying ? (this.data.audioInfo.isPlaying = !1,
      this.setData({
        audioInfo: this.data.audioInfo
      }), void this.innerAudioContext.stop()) : void this.startPlayAudio(this.data.audioInfo.tempFilePath);
  }

}

const checkPermission = function (t, e, n) {
  wx.getSetting({
    success: function (a) {
      null == a.authSetting[t] ? wx.authorize({
        scope: t,
        success: function () {
          n();
        },
        fail: function () {

        }
      }) : a.authSetting[t] ? n() : (wx.showModal({
        title: "提示",
        content: e,
        success: function (t) {
          t.confirm ? (wx.openSetting({})) : t.cancel;
        }
      }));
    }
  });
}



const initInnerAudioContext = function () {
  this.innerAudioContext = wx.createInnerAudioContext(), this.innerAudioContext.autoplay = !0,
    this.innerAudioContext.onPlay(this.innerAudioPlay), this.innerAudioContext.onTimeUpdate(this.innerAudioTimeUpdate),
    this.innerAudioContext.onError(this.innerAudioError), this.innerAudioContext.onEnded(this.innerAudioEnd),
    this.innerAudioContext.onPause(this.innerAudioPause), this.innerAudioContext.onStop(this.innerAudioStop);
}

const innerAudioPlay = function () {
  null != this.data.audioInfo && (this.data.audioInfo.isPlaying = !0,
    this.data.audioInfo.progress = 0, this.setData({
      audioInfo: this.data.audioInfo
    }));
}
const innerAudioTimeUpdate = function () {

  if (null != this.innerAudioContext && null != this.data.audioInfo) {
    if (this.data.isLocalAudioPlay) {
      var t = this.innerAudioContext.duration;
      return console.log("publish innerAudioTimeUpdate => duration: " + this.innerAudioContext.duration),
        void(t > 0 && (this.data.audioInfo.duration = 1e3 * t, this.data.audioInfo.second = (parseInt(this.data.audioInfo.duration) / 1e3).toFixed(1),
          this.data.isLocalAudioPlay = !1, this.data.audioInfo.isPlaying = !1, this.setData({
            audioInfo: this.data.audioInfo
          }), this.innerAudioContext.stop()));
    }
    var i = this.innerAudioContext.currentTime;
    if (i > 0) {
      var a = Math.ceil(10 * i);
      a > this.data.audioInfo.progress && (a > 10 * this.data.audioInfo.second && (a = 10 * this.data.audioInfo.second),
        this.data.audioInfo.progress = a, this.setData({
          audioInfo: this.data.audioInfo
        }));
    }
  }
}
const innerAudioError = function (t) {
  //  e.log("publish => audio play onError"), e.log(t);
}
const innerAudioEnd = function () {
  null != this.data.audioInfo && (this.data.audioInfo.isPlaying = !1,
    this.data.audioInfo.progress = 10 * this.data.audioInfo.second, this.setData({
      audioInfo: this.data.audioInfo
    }));
}
const innerAudioPause = function () {
  null != this.data.audioInfo && (this.data.audioInfo.isPlaying = !1,
    this.setData({
      audioInfo: this.data.audioInfo
    }));
}
const innerAudioStop = function () {
  null != this.data.audioInfo && (this.data.audioInfo.isPlaying = !1,
    this.setData({
      audioInfo: this.data.audioInfo
    }));
}

const editTap = function (t) {
  let id = t.currentTarget.dataset.id;
  let index = t.currentTarget.dataset.index;
  this.setData({
    delindex: index,
    showDialog: !this.data.showDialog,
    id: id,
  })

}


const tapcommentlike = function (e) {
  let id = e.currentTarget.id;
  let index = e.currentTarget.dataset.index;
  let that = this;
  markComment({
      id: id
    }).then(res => {
      if (res.status == 200) {
        that.data.comments[index].islike = true;
        that.data.comments[index].likes += 1;
        that.setData({
          comments: that.data.comments,
        })
      } else if (res.status == 202) {
        that.data.comments[index].islike = false;
        that.data.comments[index].likes -= 1;
        that.setData({
          comments: that.data.comments,
        })
      }
    })
    .catch(err => {
      if (err.message == "未授权登录用户,不允许操作" || err.message == "授权信息有误,无法查询用户") {
        that.data.currentConfig.show = true;
        that.setData({
          currentConfig: that.data.currentConfig,
        })
      }
    })
}


/**
 * 发表评论
 */

const addComment = function (e) {
  if (!this.data.iscanpublish && this.data.inputValue.length == 0) {
    wx.showToast({
      title: '随便说点什么吧',
    })
    return;
  }
  let that = this;
  let args = {};
  let comment_content = this.data.inputValue
  args.content = comment_content ? comment_content.trim() : ''
  args.id = this.data.id
  args.images = this.data.imagesubject;
  args.duration = this.data.duration
  args.displayDuration = this.data.audio_time
  args.audio = this.data.audio
  args.parent = this.data.parent
  if (!this.data.user) {
    wx.navigateTo({
      url: '/pages/login/login',
    })
  } else if (args.content.length === 0 && !this.data.imagesubject && !this.data.audio) {
    wx.showModal({
      title: '提示',
      content: '评论内容不能为空'
    })
  } else {
    wx.showLoading({
      title: '正在提交',
      mask: true,
    })
    addComments(args).then(res => {
        if (res.status === 200) {
          wx.hideLoading();
          let templates = app.globalData.templates.comments // 模板 ID
          wx.requestSubscribeMessage({
            tmplIds: templates,
            success(res) {
              let template_id = JSON.stringify(res)
              for (let i = 0; i < templates.length; i++) {
                let template = templates[i]
                let response = template_id.replace(template, "status")
                let subscribe = JSON.parse(response)
                app.vPush.addFormId(template, subscribe.status)
              }
              if (res.errMsg == "requestSubscribeMessage:ok") {
                wx.showToast({
                  // title: '订阅消息完成',
                  icon: 'success',
                  duration: 1000
                })
              }
            },
            fail: function (res) {

            }
          })

          this.setData({
            page: 1,
            showTextarea: false,
            content: "",
            comments: [],
            imagesubject: [],
            placeholder: "说点什么吧...",
            isFocus: false,
            modalTarget: '',
            voiceshow: false,
            isLastPage: false,
            audio: '',
            audio_time: 0,
            duration: 0,
            images: '',
            inputValue: '',
            is_complete_voice: false,
          })
          setTimeout(function () {
            wx.showToast({
              title: res.message,
              icon: 'success',
              duration: 900,
            })
          }, 900)
          that.data.detail.comments += 1;
          that.setData({
            detail: that.data.detail,
          })
          this.getPostsComments({
            id: this.data.id,
            page: this.data.page
          });
          if (!this.data.isComments) {
            this.setData({
              isComments: true,
              placeholder: '',
              modalTarget: ''
            })
          }
          //  this.getPostsComments()
        } else if (res.status === 500) {
          wx.showModal({
            title: '提示',
            content: '评论失败，请稍后重试。'
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '必须授权登录才可以评论'
          })
        }
      })
      .catch(err => {
        if (err.message == "授权信息有误") {
          wx.hideLoading({
            success: (res) => {},
          })
          that.data.currentConfig.show = true;
          that.setData({
            currentConfig: that.data.currentConfig,
          })
        }
        if (err.message == "内容含有违规关键词") {
          wx.hideLoading();
          wx.showToast({
            title: err.message,
          })
        }
      })
  }
}

const onUserClick = function (e) {
  let id = e.currentTarget.dataset.uid;
  wx.navigateTo({
    url: '/pages/user/user?id=' + id,
  })
}

const routeClubDetail = function (e) {
  let id = e.currentTarget.dataset.id;
  wx.navigateTo({
    url: '/pages/circle/list?id=' + id,
  })
}

const getSearchPosts = function (args) {
  getpddSearch(args).then(res => {
      if (res.length < 10) {
        this.setData({
          isLastPage: true,
          loadtext: '到底啦',
          showloadmore: false
        })
      }
      let args = {}
      if (this.data.isPull) {
        args.posts = [].concat(this.data.posts, res.goods_search_response.goods_list)
        args.page = this.data.page + 1
      } else if (this.data.isBottom) {
        args.posts = [].concat(this.data.posts, res.goods_search_response.goods_list)
        args.page = this.data.page + 1
      } else {
        args.posts = [].concat(this.data.posts, res.goods_search_response.goods_list)
        args.page = this.data.page + 1
      }
      if (this.data.isPull) {
        wx.stopPullDownRefresh()
      }
      if (args.posts != []) {
        args.isList = true
      }
      //wx.setNavigationBarTitle({title: res.title.rendered})
      args.isPull = false
      this.setData(args)
    })
    .catch(err => {
      this.setData({
        isPull: false,
        isLastPage: true,
        loadtext: '到底啦',
      })
      wx.stopPullDownRefresh()
    })
}


const gotoTags = function (e) {
  const id = e.currentTarget.id;
  const name = e.currentTarget.dataset.name
  wx.navigateTo({
    url: '/pages/tags/tags?id=' + id + '&name=' + name,
  })
}


const clickLike = function (e) {
  let args = {}
  let that = this;
  if (!this.data.user) {
    wx.navigateTo({
      url: '/pages/login/login',
    })
    return
  }
  args.id = e.currentTarget.id;
  like(args).then(res => {
    if (res.status === 200) {
      wx.showToast({
        title: '谢谢点赞!',
        icon: 'success',
        duration: 900,
      })
      that.data.detail.likes += 1;
      that.setData({
        detail: that.data.detail,
        isLike: true
      })
    }
    if (res.status === 202) {
      wx.showToast({
        title: '取消点赞!',
        icon: 'success',
        duration: 900,
      })
      that.data.detail.likes -= 1;
      that.setData({
        detail: that.data.detail,
        isLike: false
      })

    }
  }).catch(err => {
    if (err.message = "授权信息有误") {
      that.data.currentConfig.show = true;
      that.setData({
        currentConfig: that.data.currentConfig,
      })
    }
  })
}


const clickFav = function (e) {
  let args = {}
  let that = this;
  if (!this.data.user) {
    wx.navigateTo({
      url: '/pages/login/login',
    })
    return
  }
  args.id = e.currentTarget.id;
  fav(args).then(res => {
    if (res.status === 200) {
      wx.showToast({
        title: '谢谢收藏!',
        icon: 'success',
        duration: 900,
      })
      that.data.detail.favs += 1;
      that.setData({
        detail: that.data.detail,
        isFav: true
      })
    }
    if (res.status === 202) {
      wx.showToast({
        title: '取消收藏!',
        icon: 'success',
        duration: 900,
      })
      that.data.detail.favs -= 1;
      that.setData({
        detail: that.data.detail,
        isFav: false
      })

    }
  }).catch(err => {
    if (err.message = "授权信息有误") {
      that.data.currentConfig.show = true;
      that.setData({
        currentConfig: that.data.currentConfig,
      })
    }
  })
}

const getUserBySearch = function (args) {
  let that = this;
  getUserSearch(args).then(res => {
      if (res.length <= 10) {
        this.setData({
          isLastPage: true,
          loadtext: '到底啦',
        })
      }
      if (this.data.bottom) {
        args.page = this.data.page + 1
        args.userList = [].concat(this.data.userList, res)
      } else {
        args.page = this.data.page + 1;
        args.userList = res;
      }
      that.setData(args);
    })
    .catch(err => {
      console.log(err)
    })


}


/**
 * 生成海报
 */
const isPrefix = function () {
  let that = this;
  wx.showLoading({
    title: '海报生成中...',
  })
  let args = {};
  args.id = that.data.id
  args.path = "/pages/detail/detail?id=" + that.data.id + "&type=" + that.data.type
  getCodeImg(args).then(res => {
    let time = util.formatDate(new Date());
    let date = util.getDates(1, time);
    let thumble = res.cover;
    let qrcode = res.qrcode;
    let title = that.data.detail.title.rendered;
    let detail = that.data.detail.excerpt.rendered;
    let name = that.data.detail.author.name;
    that.setData({
      template: new Card().palette(date[0].week, date[0].time, thumble, qrcode, title, detail, name),
      showPainter: true,
      shareshow: false,
    });
  })
}


/**
 * 关注/取消关注
 */

const actionFollow = function (e) {
  let data = {}
  let that = this;
  let index = e.currentTarget.dataset.index
  let id = e.currentTarget.id // 关注的用户id
  let action = e.currentTarget.dataset.action // 关注动作：follow 取关动作 disfollow
  let type = e.currentTarget.dataset.type
  data.id = id
  data.action = action
  if (!this.data.user) {
    wx.navigateTo({
      url: '/pages/login/login',
    })
    return;
  }
  if (id == 0) {
    wx.showToast({
      title: '匿名用户不能关注',
    })
    return;
  }
  updateFollow(data).then(res => {
      if (res.message == "取关成功") {
        console.log(1);
        if (type == 'forums') {
          that.data.posts[index].author.status = 'follow';
          that.setData({
            posts: that.data.posts
          })
        } else if (type == 'user') {
          that.data.followlist[index].status = false;
          that.setData({
            followlist: that.data.followlist
          })
        } else {
          that.setData({
            isFollow: false,
          })
        }
      } else if (res.message == "关注成功") {
        if (type == 'forums') {
          that.data.posts[index].author.status = 'disfollow';
          that.setData({
            posts: that.data.posts,
          })
        } else if (type == 'user') {
          that.data.followlist[index].status = true;
          that.setData({
            followlist: that.data.followlist
          })
        } else {
          that.setData({
            isFollow: true,
          })
        }
      }


    })
    .catch(err => {
      if (err.message == "授权信息有误") {
        that.data.currentConfig.show = true;
        that.setData({
          currentConfig: that.data.currentConfig,
        })
      }
    })
}

const getSiteInfos = function () {
  getSiteInfo().then(res => {
      let args = {}
      args.title = res.name
      args.description = res.description
      args.version = res.version
      args.cover = res.cover
      if (res.advert) {
        wx.setStorageSync('advert', res.advert)
      }
      this.setData(args)
    })
    .catch(err => {
      console.log(err)
    })
}

const updataShareCredit = function (userId, openId) {
  let data = {
    uid: userId,
    openid: openId
  }
  updataShareCredits(data).then(res => {
    console.log(res);
  })

}

const addAttachment = function () {
  var t = this;
  wx.chooseMessageFile({
    count: 1,
    type: "file",
    extension: ["doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf"],
    success: function (i) {
      wx.showLoading({
        title: '正在上传',
      })
      var o = i.tempFiles[0],
        n = o.path,
        s = n.lastIndexOf("."),
        d = n.substring(s + 1, n.length);
      uploadMedia(n).then(res => {
        wx.hideLoading();
        t.setData({
          mediaType: 3,
          attachmentInfo: {
            name: o.name.substring(0, o.name.lastIndexOf(".")),
            path: res.url,
            size: o.size,
            fileType: d,
          }
        });
      }).catch(err => {
        if (err.message == "未授权登录用户,不能上传") {
          that.setData({
            showlogin: true,
            nologin: true
          })
        }
      })
    }
  });
}

const onAttachmentClicks = function (e) {
  var that = this;
  var filePath = e.currentTarget.dataset.url; //对应的网络路径，可以是内网的或者外网
  var fileType = e.currentTarget.dataset.type.toLowerCase();
  wx.showLoading({
    title: '正在加载文档',
  })
  wx.downloadFile({ //下载对应文件
    url: filePath,
    success: function (res) {
      var filePath = res.tempFilePath; //文件路径    
      wx.openDocument({
        filePath: filePath, // 装载对应文件的路径
        fileType: fileType, // 指定打开的文件类型
        showMenu: true, // 右上角的菜单转发分享操作
        success: function (res) {
          console.log("打开成功");
          wx.hideLoading();
        },
        fail: function (res) {
          wx.hideLoading();
          wx.showToast({
            title: '打开失败',
          })
        }
      })
    },
    fail: function (res) {
      console.log(res);
    }
  })
}


module.exports = function (obj) {
  obj.getProfiles = getProfiles;
  obj.getUserInfoFun = getUserInfoFun;
  obj.authCancel = authCancel;
  obj.addPictures = addPictures;
  obj.addVideo = addVideo;
  obj.selectAudio = selectAudio;
  obj.uploadVideoToMedia = uploadVideoToMedia;
  obj.getPostsComments = getPostsComments;
  obj.onRecordFinish = onRecordFinish;
  obj.onAudioPlay = onAudioPlay;
  obj.startPlayAudio = startPlayAudio;
  obj.onAudioDelete = onAudioDelete;
  obj.jumpAnalysis = jumpAnalysis;
  obj.checkPermission = checkPermission;
  obj.initInnerAudioContext = initInnerAudioContext;
  obj.innerAudioPlay = innerAudioPlay;
  obj.innerAudioTimeUpdate = innerAudioTimeUpdate;
  obj.innerAudioError = innerAudioError;
  obj.innerAudioEnd = innerAudioEnd;
  obj.innerAudioPause = innerAudioPause;
  obj.innerAudioStop = innerAudioStop;
  obj.editTap = editTap;
  obj.audioToMedia = audioToMedia;
  obj.tapcommentlike = tapcommentlike;
  obj.addComment = addComment;
  obj.onUserClick = onUserClick;
  obj.routeClubDetail = routeClubDetail;
  obj.getSearchPosts = getSearchPosts;
  obj.gotoTags = gotoTags;
  obj.clickLike = clickLike;
  obj.clickFav = clickFav;
  obj.isPrefix = isPrefix;
  obj.getUserBySearch = getUserBySearch;
  obj.actionFollow = actionFollow;
  obj.getSiteInfos = getSiteInfos;
  obj.updataShareCredit = updataShareCredit;
  obj.addAttachment = addAttachment;
  obj.onAttachmentClicks = onAttachmentClicks;
  obj.getBanners = getBanners;
  obj.getRankLists = getRankLists
}